package com.dwxt.cdms.service.wx;

import com.dwxt.cdms.dao.WxBindMapper;
import com.dwxt.cdms.entity.Customer;
import com.dwxt.cdms.entity.WxBind;
import com.dwxt.cdms.service.CustomerService;
import com.dwxt.cdms.util.XMLUtil;
import com.dwxt.cdms.util.wx.ReplyTextMsg;
import com.dwxt.common.util.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

@Slf4j
@Service
public class BindService {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private WxBindMapper wxBindMapper;


    /**
     * 绑定公众号
     */
    public String bindUser(String phone, String openId) {
        if (RegexUtils.checkMobile(phone)) {
            Customer customer = customerService.selectOrInsert(phone);
            //用户存在且未绑定
            if (customer != null && !customerService.isWxBind(customer.getId())) {
                WxBind wxBind = new WxBind();
                wxBind.setCustomerId(customer.getId());
                wxBind.setOpenid(openId);
                wxBind.setStatus(1);
                wxBindMapper.insertSelective(wxBind);
                return "绑定成功";
            } else {
                return "异常用户,请确认信息后重试";
            }
        } else {
            return "请输入正确电话";
        }
    }

    /**
     * 解绑公众号
     */
    public String unBindUser(String phone, String openId) {
        if (RegexUtils.checkMobile(phone)) {
            Customer customer = customerService.selectOrInsert(phone);
            if (customer != null && customerService.isWxBind(customer.getId())) {
                WxBind wxBind = new WxBind();
                wxBind.setCustomerId(customer.getId());
                wxBind.setOpenid(openId);
                wxBind.setStatus(0);
                wxBindMapper.updateByPrimaryKeySelective(wxBind);
                return "解绑成功";
            } else {
                return "异常用户,请确认信息后重试";
            }
        } else {
            return "请输入正确电话";
        }
    }

    public void replyMessage(String message, HttpServletResponse responseOut) throws IOException {
        Writer out = new BufferedWriter(new OutputStreamWriter(responseOut.getOutputStream()));
        Document document = XMLUtil.readString2XML(message);
        Element root = document.getRootElement();
        String MsgType = XMLUtil.readNode(root, "MsgType");
        String openid = XMLUtil.readNode(root, "FromUserName");
        //提交为文字类
        if (MsgType.equals("text")) {
            ReplyTextMsg textMsg = new ReplyTextMsg();
            String content = XMLUtil.readNode(root, "Content");
            if (content.equals("绑定")) {
                textMsg.setContent("请按一下格式回复消息进行绑定账号\n"
                        + "格式：绑定#平台绑定手机号\n"
                        + "例如：绑定#18358888888");
            } else if (content.equals("解绑")) {
                textMsg.setContent("请按一下格式回复消息进行解绑账号\n"
                        + "格式：解绑#平台绑定手机号\n"
                        + "例如：解绑#18358888888");
            } else if (content.contains("绑定#")) {
                String phone = content.replace("绑定#", "");
                textMsg.setContent(bindUser(phone, openid));
            } else if (content.contains("解绑#")) {
                String phone = content.replace("解绑#", "");
                textMsg.setContent(unBindUser(phone, openid));
            } else {
                textMsg.setContent("输入正确命令后重试");
            }
            textMsg.setFromUserName(XMLUtil.readNode(root, "ToUserName"));
            textMsg.setToUserName(XMLUtil.readNode(root, "FromUserName"));
            textMsg.setCreateTime();
            //将XML消息的参数都转化内容回复给微信
            XMLUtil.content = "";
            String nodeString = XMLUtil.readNodes(root);
            textMsg.setMsgType("text");
            try {
                //将对象转化为XML
                String replyMsg = textMsg.Msg2Xml();
                out.write(replyMsg);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            //时间提交
        } else if (MsgType.equals("event")) {
            try {
                // String Status = XMLUtil.readNode(root, "Status");
                // log.info("用户：" + openid + "消息模板推送信息回调" + Status);
                String eventKey = XMLUtil.readNode(root, "EventKey");
                if (eventKey.equals("abx_fwrx")) {
                    ReplyTextMsg textMsg = new ReplyTextMsg();
                    textMsg.setFromUserName(XMLUtil.readNode(root, "ToUserName"));
                    textMsg.setToUserName(XMLUtil.readNode(root, "FromUserName"));
                    textMsg.setCreateTime();
                    textMsg.setMsgType("text");
                    textMsg.setContent("968008");
                    //将对象转化为XML
                    String replyMsg = textMsg.Msg2Xml();
                    out.write(replyMsg);
                    out.close();
                }
            } catch (Exception e) {

            }
        }
    }


}
